<?
$lDetailedPage=1;
include_once("header_inc.php");

$ad_id=round(getParam("id",""));
$lPrint=getParam("print","");
$fromMyItems = getParam("fromMyItems",0);
$returnLink = getParam("return_link","");

// If setting is not set, use these defaults...
if (!$set_outer_color) { $set_outer_color = "#A9B8D1"; 	}
if (!$set_inner_color) { $set_inner_color = "#FFFFFF"; 	}
if (!$set_descr_color) { $set_descr_color = "#FFFFFF"; 	}
if (!isset($set_descr_cell)) {	$set_descr_cell = 10; 	}
if (isset($preview)) { $ad_id = $preview; $validation = 0; 	}

if (!$ad_id)
	criticalError(LA_ERROR,LA_ERROR_NO_ID);

/*JMR: validación de avisos no PAGOS, pero dejamos que se puedan ver los propios del cliente  */
$owner = "-1";
if(!empty($_SESSION["valid_user"])){		
	$owner = $_SESSION["valid_user"];		
}
if ($set_validation == 1 && getParam("preview","")=="") {	
	$val_string = " AND ((ad_is_validated = 1 AND ad_enabled = 1) OR ad_owner = ".$owner.") "; 
} 
else { $val_string = " AND (ad_enabled = 1 OR ad_owner = ".$owner." ) "; }



$temp_table = "(select a.*,b.nombre as provincia from $ads_tbl a left join $prov_tbl b on a.ad_provincia = b.id) as x";
$sql_links = "select * from $temp_table, $cat_tbl, $usr_tbl where cat_id=ad_cat_id AND user_id=ad_owner AND ad_id=$ad_id $val_string";
$result_from_ad = q($sql_links);
$row_from_ad=mysql_fetch_array($result_from_ad);

if (mysql_num_rows($result_from_ad) == 0)
	criticalError(LA_AD_REMOVED_CAPTION,formatString(LA_AD_REMOVED_CONTENT,array("http://$set_url")));
	
$sitetitle = $row_from_ad["ad_title"];
$ad_description = $row_from_ad["ad_description"];
$userid = $row_from_ad["user_id"];
$ad_date = $row_from_ad["ad_date"];
$ad_views = $row_from_ad["ad_views"];
$ad_votes = $row_from_ad["ad_votes"];
$ad_voters = $row_from_ad["ad_voters"];
$ad_totalscore = $row_from_ad["ad_totalscore"];
$votes = $row_from_ad["user_votes"];
$voters = $row_from_ad["user_voters"];
$name = $row_from_ad["user_name"];
$email = $row_from_ad["user_email"];
$catname = $row_from_ad["cat_name"];
$catid = $row_from_ad["cat_id"];
$tipoOperacion = getTipoDeOperacion($catid);
$vendor_url = $row_from_ad["user_vendor_url"];
$vendor_homepage = $row_from_ad["user_vendor_homepage"];
$sold = $row_from_ad["ad_is_sold"];
$cattpl = $row_from_ad["cat_tpl"];
$datestamp = $row_from_ad["ad_date"];
$ad_has_picture = $row_from_ad["ad_has_picture"];
$is_vendor = $row_from_ad["user_is_vendor"];
$hide_email = $row_from_ad["user_hide_email"];
$img_stored = $row_from_ad["img_stored"];
$user_id = $row_from_ad["user_id"];
$expire_days = $row_from_ad["ad_expires_after_days"];
$ad_expires=formatDateShort($row_from_ad["ad_date_expire"]);
$timestamp_expire_date=$row_from_ad["ad_date_expire"];
$ad_added=formatDateShort($row_from_ad["ad_date"]);
$pagename= $sitename . " - " . cleanInput($sitetitle);
$meta_desc=cleanInput(dotString($ad_description,150));
$lRegionId = $row_from_ad["ad_region"];

$lPrecio = $row_from_ad["ad_precio"];
$lMoneda = $row_from_ad["ad_moneda"];
$lProvincia = $row_from_ad["provincia"];
$lIdLocalidad = $row_from_ad["ad_localidad_id"];

// Start template system
$tplDetail=new TplLoad;


if (($_SESSION["valid_user"] !="") && (getParam("submit","") !="") && (getParam("comment_body","") !=""))
{
	$lfBody=strToDb(getParam("comment_body",""));
	$lfAdId=$ad_id;
	$lfUser=$_SESSION["valid_user"];
	$lResComment=q("select user_name,user_email from $usr_tbl where user_id=$lfUser");
	if (mysql_num_rows($lResComment)>0)
	{
		$lRowComment=mysql_fetch_array($lResComment);
		$lFromName=$lRowComment["user_name"];
		$lFromEmail=$lRowComment["user_email"];
	
		$lSql="insert into $com_tbl (comment_body,comment_date,comment_userid,comment_ad,comment_ip) values ('$lfBody',".time().",$lfUser,$lfAdId,'".getRemoteIp()."')";
		$lCommentRes=q($lSql);

		$lContactArray=array("$name","$email","","$set_sitename","".getRemoteIp()."","http://$set_url/".linkDetail($ad_id),"$sitetitle","$lFromName","$lFromEmail","$lfBody","$lfUser");
		$lSubject = formatString(LA_MAIL_COMMENT_SUBJECT, $lContactArray);
		$lBody = formatString(LA_MAIL_COMMENT_BODY, $lContactArray);
		if($lSubject=="")
		{
			$lSubject = getParam("subject","");			
		}
		
		//echo "SUBJECT: " . $lSubject . "<p>BODY: " . $lBody . "<p>Email to:" . $lContactEmail;
		sendEmail($email,$lFromEmail,$lSubject,$lBody);	
		$lCommentDone=1;
	}	
}

if (getParam("del","") && $set_comment_admin_del)
{
	if ($_SESSION["valid_user"]==$user_id)
	{
		q("delete from $com_tbl where comment_id=" . getParamInt("del","") . " AND comment_ad=$ad_id");
	}
}
$lSql="select * from $com_tbl where comment_ad=" . $ad_id . " order by comment_id desc";
$lComment=q($lSql);
$i=0;
while ($lRow=mysql_fetch_array($lComment))
{
	$lComments[$i]["comment_body"]=strEnc($lRow["comment_body"]);
	$lComments[$i]["comment_id"]=$lRow["comment_id"];
	$lComments[$i]["comment_userid"]=$lRow["comment_userid"];
	$lComments[$i]["comment_date"]=formatDateShort($lRow["comment_date"]);
	$lSq="select user_name from $usr_tbl where user_id=" . $lRow["comment_userid"];
	$lResult=q($lSq);
	$lRow2=mysql_fetch_array($lResult);
	$lComments[$i]["comment_by"]=strEnc($lRow2["user_name"]);
	
	$i++;
}
$tplDetail->assign("comment_list",$lComments);

// END comment system
if ($lRegionId)
{
	$tplDetail->assign("regionid",$lRegionId);
	$lRegArray=getLevelRegion($lRegionId,"");
	if (is_array($lRegArray))
		$tplDetail->assign("region",array_reverse($lRegArray));
}

$tplDetail->assign("isLoggedIn",$_SESSION["valid_user"]);
$tplDetail->assign("set_outer_color",$set_outer_color);
$tplDetail->assign("set_inner_color",$set_inner_color);
$tplDetail->assign("set_descr_color",$set_descr_color);
$tplDetail->assign("set_descr_cell",$set_descr_cell);
$tplDetail->assign("set_comment_system",$set_comment_system);
$tplDetail->assign("set_comment_admin_del",$set_comment_admin_del);
$tplDetail->assign("id_ad","$ad_id");
$tplDetail->assign("ad_id","$ad_id");
$tplDetail->assign("ad_link",linkDetail($ad_id));

$tplDetail->assign("ad_title",strEnc("$sitetitle"));
$tplDetail->assign("ad_added","$ad_added");
$tplDetail->assign("ad_hits","$ad_views");
$tplDetail->assign("ad_expire","$ad_expires");
$tplDetail->assign("ad_catid","$catid");
$tplDetail->assign("tipoOperacion",$tipoOperacion);
$tplDetail->assign("ad_username",strEnc("$name"));
$tplDetail->assign("ad_email","$email");
$tplDetail->assign("ad_catname",strEnc($row_from_ad["cat_name"]));
$tplDetail->assign("banner","$lBanner");
$tplDetail->assign("region_name",getRegionName($lRegionId));
$tplDetail->assign("googlemaps",$set_googlemap_code);
$tplDetail->assign("set_currency_text","$set_currency_text");
$tplDetail->assign("rafleaf","$set_rapleaf_code");

$tplDetail->assign("precio","$lPrecio");
$tplDetail->assign("provincia","$lProvincia");
$tplDetail->assign("moneda","$lMoneda");
$tplDetail->assign("localidad",getLocalidadFullById($lIdLocalidad));

if ($set_rapleaf_code)
{
	$rapleaf = new Rapleaf("$set_rapleaf_code", "http://www.rapleaf.com");
	$responseObject = $rapleaf->lookup(array('email'=>$email));
	//print_r($responseObject);
	if (is_null($responseObject))
	  echo "Connection failed.\n";
	else if ($responseObject->failed())
		echo $responseObject->reason."\n";
	else {
	  //if profile_stats is set that means this is a "profile not found" response
	  if (isset($responseObject->profile_stats))
	  {
	    echo $responseObject->profile_stats."\n";
	  }
	  else
	  {
	    //echo "Rating is " . $responseObject->score."\n";
	    $tplDetail->assign("rapleaf_url_small",$responseObject->image_URL_small);
	    $tplDetail->assign("rapleaf_url_main",$responseObject->image_URL_main);
	    $tplDetail->assign("rapleaf_profile_url",$responseObject->profile_URL);
	    $tplDetail->assign("rapleaf_member",$responseObject->rapleaf_member);
	    $tplDetail->assign("rapleaf_status",$responseObject->status);
	    $tplDetail->assign("rapleaf_score",$responseObject->score);
	  }
	}
}


if ($set_nl2br)
	$ad_description=nl2br($ad_description);
if ($lCommentDone)
	$tplDetail->assign("set_comment_done",1);
$tplDetail->assign("ad_description","$ad_description");
$tplDetail->assign("user_id","$user_id");
$tplDetail->assign("num_days",getHowManyDaysRemains($timestamp_expire_date,time()));
$tplDetail->assign("LA_REMOVE_FAV",urldecode(LA_REMOVE_FAV));
$tplDetail->assign("LA_ADD_FAV",urldecode(LA_ADD_FAV));
$tplDetail->assign("set_image_program",$set_image_program);

// mod_rewrite tags
$tplDetail->assign("link_adcat",linkCat($catid));
$tplDetail->assign("link_aduser",linkUser($user_id));


if ($set_detail_login_need==1)
	check_valid_user("");

if ($hide_email==1)
	$tplDetail->assign("hide_email",1);
else 
	$tplDetail->assign("email","$email");

	
// Member Rating
if ($set_vote_on_member)
		$tplDetail->assign("rate_member",$set_vote_on_member);
if ($set_ratemem_login_need)
		$tplDetail->assign("rate_member_requires_login","$set_ratemem_login_need");
if ($voters > 0)
	$votes = round($votes/$voters, 1);
else {
	$votes=0;
	$voters=0;
}
$tplDetail->assign("sold","$sold");
$tplDetail->assign("ad_member_votes","$votes");
$tplDetail->assign("ad_member_voters","$voters");

// Ad Rating
if ($set_rate)
		$tplDetail->assign("rate_ad","$set_rate");
if ($set_rate_ad_require_member)
		$tplDetail->assign("rate_ad_requires_login","$set_rate_ad_require_member");

// Get image rating
$lStr=getStarRating($ad_totalscore);

$tplDetail->assign("ad_vote_img_result","$lStr");
$tplDetail->assign("ad_ad_votes","$ad_votes");
$tplDetail->assign("ad_ad_voters","$ad_voters");
$tplDetail->assign("ad_totalscore","$ad_totalscore");

	
// Code for prev next result
if ($sold == 1)
	$tplDetail->assign("isSold",1);

$tplDetail->assign("IS_VENDOR","$is_vendor");
$tplDetail->assign("VENDOR_URL",strEnc($vendor_url));
$tplDetail->assign("VENDOR_HOMEPAGE",strEnc($vendor_homepage));	

if($fromMyItems == 1 && !empty($_SESSION["valid_user"])){
	
	$sql_prevad_id = "select ad_id from $ads_tbl, $cat_tbl, $usr_tbl ".
					 " where cat_id=ad_cat_id AND ad_owner=user_id AND ad_id < $ad_id AND ad_owner=".$_SESSION["valid_user"]." $val_string ". 
					 " order by ad_id desc limit 1";
	
	$result_prevad_id = q($sql_prevad_id);
	$row_prev = mysql_fetch_array($result_prevad_id);
	$prevad_id = $row_prev["ad_id"];
	
	$sql_nextad_id = "select ad_id from $ads_tbl, $cat_tbl, $usr_tbl ".
					  "where cat_id=ad_cat_id AND ad_owner=user_id AND ad_id > $ad_id AND ad_owner=".$_SESSION["valid_user"]." $val_string ". 
					  "order by ad_id asc limit 1";
	
	$result_nextad_id = q($sql_nextad_id);
	$row_next = mysql_fetch_array($result_nextad_id);
	$nextad_id = $row_next["ad_id"];

}else{
	
	$sql_prevad_id = "select ad_id from $ads_tbl, $cat_tbl, $usr_tbl where cat_id=ad_cat_id AND ad_owner=user_id AND ad_id < $ad_id AND cat_id = $catid $val_string order by ad_id desc limit 1";
	$result_prevad_id = q($sql_prevad_id);
	$row_prev = mysql_fetch_array($result_prevad_id);
	$prevad_id = $row_prev["ad_id"];
	
	$sql_nextad_id = "select ad_id from $ads_tbl, $cat_tbl, $usr_tbl where cat_id=ad_cat_id AND ad_owner=user_id AND ad_id > $ad_id AND cat_id = $catid $val_string order by ad_id asc limit 1";
	$result_nextad_id = q($sql_nextad_id);
	$row_next = mysql_fetch_array($result_nextad_id);
	$nextad_id = $row_next["ad_id"];

}

// PREV NEXT AD
if ($prevad_id)
{
	$lLinkPrev=linkDetail($prevad_id);
	if (ereg("\?",$lLinkPrev))
		$lLinkPrev.="&amp;catid=" . $catid."&amp;fromMyItems=1";
	else
		$lLinkPrev.="?catid=" . $catid."&amp;fromMyItems=1";
		
	if($fromMyItems == 1){
		$str_nav.="<a href='$lLinkPrev&amp;fromMyItems=1'>";
	}else{
		$str_nav.="<a href='$lLinkPrev'>";
	}
	$str_nav.="<img src='layout_images/arrow-back.gif' border='0' alt='' /> ".LA_P."</a>";
	if($fromMyItems == 1){	
		$tplDetail->assign("prev_link",$lLinkPrev);
	}
}
$str_nav.="&nbsp;&nbsp;&nbsp;";
if ($nextad_id)        
{
	$lLinkNext=linkDetail($nextad_id);
	if (ereg("\?",$lLinkNext))
		$lLinkNext.="&amp;catid=" . $catid."&amp;fromMyItems=1";
	else
		$lLinkNext.="?catid=" . $catid."&amp;fromMyItems=1";
		
	if($fromMyItems == 1){
		$str_nav.="<a href='$lLinkNext&amp;fromMyItems=1'>";
	}else{
		$str_nav.="<a href='$lLinkNext'>";
	}
	$str_nav.=LA_N . " <img src='layout_images/arrow-forw.gif' border='0' alt='' /></a>"; 
	
	if($fromMyItems == 1){
		$tplDetail->assign("next_link",$lLinkNext);
	}
	
}
//JMR: Return to search link
if($fromMyItems != 1){
	if(!empty($returnLink)){
		$tplDetail->assign('return_link',base64_decode($returnLink));
	}
}
//END JMR
//JMR: Calcular Ads Similares (identica Categoría)
$condtionArray = array( 0 => 'ad_cat_id = '.$catid, 1=> 'ad_id!='.$ad_id); 
$order = array();
$order[0] = array( 0 => 'ad_is_premium', 1=> 'desc');
$order[1] = array( 0 => 'ad_date', 1 => 'desc');
$similarAds = getAds($condtionArray,10,$order);
foreach ($similarAds as $key => $record){
	$similarAds[$key]["IMAGEYESNO"] = generateImageLinks($record['ad_id'],$record['ad_has_picture']);
}
$tplDetail->assign("similarAds",$similarAds);
//JMR: END

$tplDetail->assign("navigation","$str_nav");
	
if (getParam("contact","")!="")
	include "contact.php";
if (getParam("tellafriend",""))
	include "tellafriend.php";

 $fExtraArray=getFieldArray($ad_id,$user_id,",",$set_language);

  /* Extra fields handling START */
$lAdArray=$fExtraArray["ad"][$ad_id];
if (is_array($lAdArray))
{
	foreach ($lAdArray as $lKey => $lValue)
	{ 
		if ($lValue["question"])
			$lAdArray[$lKey]["question"]=(constant($lValue["question"]));
		if ($lValue["description"])
			$lAdArray[$lKey]["description"]=(constant($lValue["description"]));
		if ($lValue["type"]=="p")
			$lAdArray[$lKey]["value"]=PriceFormat($lValue["value"]);
		  
			
	}
}
$lUserArray=$fExtraArray["user"][$user_id];
if (is_array($lUserArray))
{
	foreach ($lUserArray as $lKey => $lValue) 
	{
		if ($lValue["question"])
			$lUserArray[$lKey]["question"]=(constant($lValue["question"]));
		if ($lValue["description"])
			$lUserArray[$lKey]["description"]=(constant($lValue["description"]));
	}
}
 
 $tplDetail->assign("ads",$lAdArray);
 $tplDetail->assign("users",$lUserArray);


if ($set_favourites AND isset($_SESSION["valid_user"]))
{
	$sql = "select fid from $fav_tbl where f_adid=$ad_id AND f_user_id = ".$_SESSION["valid_user"];
	$r = mysql_query($sql);
	$number = mysql_num_rows($r);
	
	if ($number)
		$tplDetail->assign("fav_remove_link",1);
	else 
		$tplDetail->assign("fav_add_link",1);
}

$query = "select * from $vid_tbl where video_adid=$ad_id";
$sql_result = q($query);
while ($row=mysql_fetch_array($sql_result))
{
	
	$id = $row["video_id"];
	$filename_stored = $row["video_file"];
	$array = split("\.",$filename_stored);
	$last=count($array)-1;
	$ext=$array[$last];
	
	$videoArray[$i]["file"]=$filename_stored;
	$videoArray[$i]["id"]=$id;
	$videoArray[$i]["ext"]=strtolower($ext);
	$i++;

	
}
$tplDetail->assign("video_list",$videoArray);

$query = "select * from $doc_tbl where f_adid=$ad_id order by f_id desc";
$sql_result_doc = q ($query);
$i=0;
while ($row=mysql_fetch_array($sql_result_doc))
{
	
	$id = $row["f_id"];
	$filetype = $row["filetype"];
	$filename = $row["f_file"];
	
	$fArray[$i]["id"] = $id;
	$fArray[$i]["name"] = $filename;
	$lSize=filesize("images/docs/" . $filename);
	$fArray[$i]["size"] = round($lSize/1024);
	
	$lDisplay=ereg_replace($ad_id . "_","",$filename);
	$fArray[$i]["display_name"] = $lDisplay;
	$lExtArray=split("\.",$filename);
	$lExt=end($lExtArray);
	$fArray[$i]["ext"] = strtolower($lExt);	
	$i++;
	
}
$tplDetail->assign("doc_list", $fArray);

$query = "select id,filename from $pic_tbl where pic_ad_id=$ad_id";
$sql_result = q($query);
$num_ad_has_pictures =  mysql_num_rows($sql_result);
	
for ($i=0; $i<$num_ad_has_pictures; $i++)
{
	$row = mysql_fetch_array($sql_result);  
	$id = $row["id"];
	$filename_stored = $row["filename"];
	if(!file_exists("images/".$filename_stored)){
		$i--;
		q("delete FROM $pic_tbl where filename like '".$filename_stored."' ");
		continue;
	}
	if ($set_image_program==0)
	{
		$lSizeArray=setImageSize($filename_stored,getManualSize("small"),0);
		$imgArray[$i]["w"]=$lSizeArray[0];
		$imgArray[$i]["h"]=$lSizeArray[1];
	}
	else 
		$filename_stored=ereg_replace("tmb2","tmb1",$filename_stored);
	
	$lFileOrig=ereg_replace("_tmb1","",$filename_stored);	
	$lFileOrig=ereg_replace("_tmb2","",$lFileOrig);
		
  	$imgArray[$i]["file"]=$filename_stored;
  	$imgArray[$i]["file_large"]=$lFileOrig;
	$imgArray[$i]["id"]=$id;
	$imgArray[$i]["nr"]=$i;
	
	
	$kaigaPicture[$i]['image']['url']=$lFileOrig;
	$kaigaPicture[$i]['thumbnail']['url']=$filename_stored;
	$kaigaPicture[$i]['preview']['url']=$lFileOrig;
	
}
if ($set_image_program==0)
	$tplDetail->assign("image_max",getManualSize("small"));
$tplDetail->assign("image_list",$imgArray);
$tplDetail->assign("set_slideshow",$set_slideShow);
$tplDetail->assign("set_slideShow_sec",$set_slideShow_sec*1000);
$tplDetail->assign("set_slideShow_count_from",$set_slideShow_sec);
$tplDetail->assign("num_pictures",$num_ad_has_pictures);
$tplDetail->assign("show_still",getParam("show_still",""));

if ($num_ad_has_pictures == 0){
	$tplDetail->assign("num_pictures",1);
	$imgArray[0]["w"]=380;
	$imgArray[0]["h"]=285;	
  	$imgArray[$i]["file"]="aviso_sin_imagen.jpg";
  	$imgArray[$i]["file_large"]="aviso_sin_imagen.jpg";
//	$imgArray[$i]["id"]=$id;
	$imgArray[$i]["nr"]=0;	
	$tplDetail->assign("image_list",$imgArray);

	$kaigaPicture[$i]['image']['url']="aviso_sin_imagen.jpg";
	$kaigaPicture[$i]['thumbnail']['url']="aviso_sin_imagen.jpg";
	$kaigaPicture[$i]['preview']['url']="aviso_sin_imagen.jpg";

}
echo '<script language="javascript">
var kaiga_picture=[';
foreach ($kaigaPicture as $pic){
	echo "
	{$coma}{
		image:{
			url:'{$pic['image']['url']}'
		},
		thumbnail:{
			url:'{$pic['thumbnail']['url']}'
		},
		preview:{
			url:'{$pic['preview']['url']}'
		}
	}";
	$coma=',';
}
echo "];";
echo '</script>';

$s = "UPDATE $ads_tbl set ad_views=ad_views+1 where ad_id=$ad_id";
$result1=q($s);

$tplDetail->display("detail.tpl");
include_once("footer_inc.php");

?>